package com.common.android.utils;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.HttpURLConnection;
import java.text.DecimalFormat;

import android.net.Uri;
import android.os.Environment;
import android.text.TextUtils;
import android.util.Log;


/**
 * 文件操作相关的工具类
 * <br>Created 2014-8-20 下午7:26:06
 * @version  1.0
 * @author   luojw		
 * @see 	 
 * Copyright(c) 2009-2014, TQ Digital Entertainment, All Rights Reserved
 */
public class FileUtils {
    
    public static final String LOCAL_FILE_PREFIX = "file://";
    private static final int ARRAY_LEN = 1024; //字节数组初始化长度
   
    
    /**
     * 通过文件的HttpURLConnection来获取文件的长度
     * <br>Created 2013-8-20下午3:10:58 
     * @param urlConnection 文件的HttpURLConnection
     * @return 文件的长度
     * @author       cb
     */
    public static long getContentLength(HttpURLConnection urlConnection){
        String range = urlConnection.getHeaderField("Content-Range");
        if (TextUtils.isEmpty(range)){
            return 0;
        }
        String[] section = range.split("/");
        try {
            // Parse for the instance length
            return Long.parseLong(section[1]);
        } catch (NumberFormatException e) {
            Log.d("debug", String
                    .format("The HttpResponse contains an invalid instance-length: %s",range));
        }
        return 0;
    }

    /**
     * 获取文件的扩展名
     * <br>Created 2014-8-20 下午9:17:01
     * @param file File对象文件
     * @return 文件扩展名
     * @author       huangyx       
     */
    public static String getFileExtensionName(File file) {
        if (file != null) {
            String fileName = file.getName();
            if (fileName.length() > 0) {
                int i = fileName.lastIndexOf('.');
                if ((i > -1) && (i < (fileName.length() - 1))) {
                    return fileName.substring(i + 1);
                }
            }
        }
        return null;
    }
    
    /**
     * 获取文件的扩展名
     * <br>Created 2014-8-25 下午8:44:02
     * @param sFileName 文件名
     * @return 文件扩展名
     * @author       huangyx
     */
    public static String getFileExtensionName(String sFileName){
        int iIndex = sFileName.lastIndexOf('.');
        if (iIndex < 0) {
            // 找不到后缀时返回null
            return null;
        }
        String sType = sFileName.substring(iIndex + 1);
        return sType;
    }
    
    
   
    /**
     * 复制文件
     * <br>Created 2014-8-22 上午9:11:01 
     * @param srcFile 源文件
     * @param destFile 复制的文件
     * @return 复制成功返回true，否则返回false
     * @author       huangyx             
     */
    public static boolean copyFile(File srcFile, File destFile) {
        boolean breturn = false;
        FileInputStream src = null;
        FileOutputStream dest = null;
        try {
            src = new FileInputStream(srcFile);
            dest = new FileOutputStream(destFile);
            int byteread = 0;
            byte[] buffer = new byte[ARRAY_LEN];
            while ((byteread = src.read(buffer)) != -1) {
                dest.write(buffer, 0, byteread);
            }
            breturn = true;
        } catch (FileNotFoundException e) {
            e.printStackTrace();
            Log.v("FileFun.CopyFile()", "FileNotFoundException");
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (src != null) {
                    src.close();
                }
                if (dest != null) {
                    dest.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        return breturn;
    }  
    
    /**
     * 删除目录
     * <br>Created 2014-8-22 上午9:10:01  
     * @param objDir 要删除的目录
     * @return 删除成功返回true，否则返回false
     * @author       huangyx              
     */
    public static boolean deleteDir(File objDir) {
        File[] objarySubfs = objDir.listFiles();
        if (objarySubfs == null) {
            return false;
        }
        for (int i = 0; i < objarySubfs.length; i++) {
            if (objarySubfs[i].isFile()) {
                objarySubfs[i].delete();
            } else {
                deleteDir(objarySubfs[i]);
            }
        }
        return objDir.delete();
    }
    
    /**
     * 删除文件
     * <br>Created 2014-8-25 下午8:45:19
     * @param uri 文件的URL
     * @author       huangyx
     */
    public static void delFile(Uri uri){
        if(uri == null) {
            return;
        }
        String path  = uri.getPath();
        File file = new File(path);
        if((file != null) && (file.exists())){
            file.delete();
        }
    }
    
    /**
     * 读取文本文件
     * <br>Created 2014-8-22 下午5:26:24
     * @param file 文件
     * @return 读取文件的字符串
     * @author       huangyx
     */
    @SuppressWarnings("resource")
    public static String readTxtFile(File file){
        BufferedReader bufread;
        String readStr = null;
        String read;
        FileReader fileread;
        try {
            fileread = new FileReader(file);
            bufread = new BufferedReader(fileread);
            try {
                while ((read = bufread.readLine()) != null) {
                    readStr = readStr + read+ "\r\n";
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        }
        return readStr;
    }
    
    /**
     * 写文件
     * <br>Created 2014-8-22 下午5:27:34
     * @param file 文件
     * @param newStr 写入的字符串
     * @throws IOException  
     * @author       huangyx
     */
    public static void writeTxtFile(File file, String newStr) throws IOException {
        //先读取原有文件内容，然后进行写入操作
        String filein = newStr;
        filein = filein + "\r\n" ;
        FileWriter fw = new FileWriter(file, true);
        try {           
            fw.write(newStr);
            fw.flush();
        } catch (IOException e1) {
            e1.printStackTrace();
        } finally {
            if(fw!=null){
                fw.close();
            }
        }
    }
    
    /**
     * 以KB为单位返回文件的大小
     * <br>Created 2014-8-22 下午7:52:29
     * @param length 文件的大小
     * @return 以KB为单位返回文件的大小
     * @author       huangyx
     */
    public static String getFileLengthUnitKB(long length){
        DecimalFormat numFormat = new DecimalFormat("#.#"); 
        return numFormat.format(length / 1024.0) + "KB";
    }
    
    /**
     * 以MB/M为单位返回计算的大小
     * <br>Created 2014-11-21 下午15:13:52
     * @param length 文件的大小,单位为B
     * @param isShort true:返回"M"， false:返回"MB"
     * @return 以KB为单位返回文件的大小
     * @author       jiangwb
     */
    public static String getFileLengthUnitMB(long length,boolean isShort){
        DecimalFormat numFormat = new DecimalFormat("#.#"); 
        if(isShort){
        	return numFormat.format(length / 1048576.0) + "M";        	
        }else{
        	return numFormat.format(length / 1048576.0) + "MB";        	
        }
    }
    
    /**
     * 判定是否是支持的格式
     * <br>Created 2014-4-18上午11:17:33
     * @param sFileName 文件名或者完整文件路径
     * @param exts 支持的文件扩展名
     * @return 文件是支持的格式返回true，否则返回false
     * @author       huangszh
     */
    public static boolean isSupportExtFile(String sFileName, String[] exts){
        String ext = FileUtils.getFileExtensionName(sFileName);
        if(ext == null) {
            return false;
        }
        
        // 有找到就是支持的
        for(String extTemp: exts) {
            if(ext.equalsIgnoreCase(extTemp)){
                return true;
            }
        }
        return false;
    }
    
    /**
     * 通过文件的路径获取文件名
     * <br>Created 2014-8-25 下午8:52:26
     * @param filename 文件的路径
     * @return 文件名
     * @author       huangyx
     */
    public static String getFilename(String filename){
        if (filename.indexOf(File.separator) >=0 ){
            File file = new File(filename);
            return file.getName();
        }
        return filename;
    }
    
    /**
     * 删除文件 
     * <br>Created 2014-8-25 下午8:55:43
     * @param file File对象文件
     * @throws IOException 
     * @author       huangyx
     */
    public static void forceDelete(File file) throws IOException {
        if (file.isDirectory()) {
            FileUtils.deleteDir(file);
        } else {
            boolean filePresent = file.exists();
            if (!file.delete()) {
                if (!filePresent){
                    throw new FileNotFoundException("File does not exist: " + file);
                }
                String message = "Unable to delete file: " + file;
                throw new IOException(message);
            }
        }
    }
    
    /**
     * 清除目录 
     * <br>Created 2014-8-25 下午8:57:19
     * @param directory 目录
     * @throws IOException   
     * @author       huangyx
     */
    public synchronized static void cleanDirectory(File directory) throws IOException {
        if (!directory.exists()) {
            String message = directory + " does not exist";
            throw new IllegalArgumentException(message);
        }

        if (!directory.isDirectory()) {
            String message = directory + " is not a directory";
            throw new IllegalArgumentException(message);
        }

        File[] files = directory.listFiles();
        if (files == null) {  // null if security restricted
            throw new IOException("Failed to list contents of " + directory);
        }

        IOException exception = null;
        for (int i = 0; i < files.length; i++) {
            File file = files[i];
            try {
                forceDelete(file);
            } catch (IOException ioe) {
                exception = ioe;
            }
        }

        if (null != exception) {
            throw exception;
        }
    }
    
    /**
     * 获取内存路径 
     * <br>Created 2014-1-27上午12:51:00
     * @return 内存路径
     * @author       HuangYK
     */
    public static String getDataDirectory() {
        if (isDataDirectory()) {
            return Environment.getDataDirectory().getAbsolutePath();
        } else {
            return null;
        }
    }
 
    /**
     * 判断内存路径是否存在
     * <br>Created 2014-1-27上午12:54:47
     * @return 内存路径是存在返回true，否则返回false
     * @author       HuangYK
     */
    public static boolean isDataDirectory(){
        return Environment.getDataDirectory().exists();
    }
    
    
}
